﻿
using System;
using System.Collections;
using zyconfig;

namespace zymarc
{
    public class MarcConvert
    {
        public const char FLDEND = '\x001e';//字段开头
        public const char RECEND = '\x001d';//iso结尾
        public const char SUBFLD = '\x001f';//子字段开头
        private string m_ISOData;//iso
        private string m_Text;
        public int _kjm;

        public void GetCnNmarc()
        {
            Random ran = new Random();
            int RandKey = ran.Next(1, 999999);
            this.m_Text = "nam0" + FLDEND.ToString() + "001" + "1".PadLeft(2, '0') + DateTime.Now.ToString("yyyy") + RandKey.ToString().PadLeft(6, '0') + FLDEND.ToString() + "005" + DateTime.Now.ToString("yyyyMMddHHmmss.ff");
            this.m_Text += FLDEND.ToString() + "010  " + SUBFLD.ToString() + "a" + SUBFLD.ToString() + "bCNY";
            this.m_Text += FLDEND.ToString() + "100  " + SUBFLD.ToString() + "a" + DateTime.Now.ToString("yyyyMMdd") + "d" + DateTime.Now.ToString("yyyy") + "    em y0chiy50      ea";
            this.m_Text += FLDEND.ToString() + "1010 " + SUBFLD.ToString() + "achi";
            this.m_Text += FLDEND.ToString() + "102  " + SUBFLD.ToString() + "aCN" + SUBFLD.ToString() + "b";
            this.m_Text += FLDEND.ToString() + "105  " + SUBFLD.ToString() + "aa   z   000ad";
            this.m_Text += FLDEND.ToString() + "106  " + SUBFLD.ToString() + "ar";
            this.m_Text += FLDEND.ToString() + "2001 " + SUBFLD.ToString() + "a" + SUBFLD.ToString() + "9" + SUBFLD.ToString() + "f";
            this.m_Text += FLDEND.ToString() + "210  " + SUBFLD.ToString() + "a" + SUBFLD.ToString() + "c" + SUBFLD.ToString() + "d";
            this.m_Text += FLDEND.ToString() + "215  " + SUBFLD.ToString() + "a" + SUBFLD.ToString() + "d";
            this.m_Text += FLDEND.ToString() + "690  " + SUBFLD.ToString() + "a" + SUBFLD.ToString() + "v";
            this.m_Text += FLDEND.ToString() + "905  " + SUBFLD.ToString() + "aGSL";
            this.m_Text += FLDEND.ToString();
        }

        public string MarcText
        {
            get { return this.m_Text; }
            set { this.m_Text = value; }
        }
        

        public string ISOData
        {
            get { return this.m_ISOData; }
            set { this.m_ISOData = value; }
        }
        /// <summary>
        /// Calis转国图，返回marc文本
        /// </summary>
        public void Ca2Cn()
        {
            string[] strArray = this.m_Text.Split(new char[] { '\x001e' });
            string str = "";
            ArrayList list = new ArrayList();
            for (int i = 0; i <= (strArray.Length - 1); i++)
            {
                list.Add(strArray[i]);
            }
            for (int j = 0; j <= (list.Count - 1); j++)
            {
                str = list[j].ToString();
                str = str.Replace('\x001f' + "9", '\x001f' + "A");
                if (str.Length > 3)
                {
                    if (str.Substring(0, 3) == "410")
                    {
                        str = str.Substring(3, str.Length - 3);//获取除字段名外的内容
                        list[j] = "461" + str;
                    }
                    else
                        list[j] = str;
                }
            }
            str = "";
            for (int k = 0; k <= (list.Count - 1); k++)
            {
                str = str + list[k].ToString() + '\x001e';
            }
            this.m_Text = str;
            if (!string.IsNullOrEmpty(this.GetASubField("305", "a", 1)))
            {
                if (!string.IsNullOrEmpty(GetASubField("200", "e", 1)))
                    this.ReplaceSubfield("200", "e", 2, this.GetASubField("305", "a", 1));
                else
                    this.ReplaceSubfield("200", "e", 1, this.GetASubField("305", "a", 1));
            }
            if (!string.IsNullOrEmpty(this.GetASubField("306", "a", 1)))
            {
                this.ReplaceSubfield("210", "h", 1, this.GetASubField("306", "a", 1));
            }
            this.DeleteField("305", 1);
            this.DeleteField("306", 1);
        }

        /// <summary>
        /// 国图转Calis，返回marc文本
        /// </summary>
        public void Cn2Ca()
        {
            string[] strArray = this.m_Text.Split(new char[] { '\x001e' });
            string str = "";
            ArrayList list = new ArrayList();
            for (int i = 0; i <= (strArray.Length - 1); i++)
            {
                list.Add(strArray[i]);
            }
            for (int j = 0; j <= (list.Count - 1); j++)
            {
                str = list[j].ToString();
                str = str.Replace('\x001f' + "A", '\x001f' + "9");
                if (str.Length > 3)
                {
                    if (str.Substring(0, 3) == "461")
                    {
                        str = str.Substring(3, str.Length - 3);//获取除字段名外的内容
                        list[j] = "410" + str;
                    }
                    else
                        list[j] = str;
                }
            }
            str = "";
            for (int k = 0; k <= (list.Count - 1); k++)
            {
                str = str + list[k].ToString() + '\x001e';
            }
            this.m_Text = str;
            string ft = GetASubField("200", "e", 1);
            if (ft.EndsWith("版"))
            {
                this.ReplaceSubfield("305", "a", 1, ft);
                this.DeleteField("200", "e", 1);
            }
            string fte = GetASubField("200", "e", 2);
            if (fte.EndsWith("版"))
            {
                this.ReplaceSubfield("305", "a", 1, fte);
                this.DeleteField("200", "e", 2);
            }
            if (!string.IsNullOrEmpty(this.GetASubField("210", "h", 1)))
            {
                this.ReplaceSubfield("306", "a", 1, this.GetASubField("210", "h", 1));
                this.DeleteField("210", "h", 1);
            }
        }
        /// <summary>
        /// 获取子字段内容
        /// </summary>
        /// <param name="FieldTag">字段</param>
        /// <param name="SubTag">子字段</param>
        /// <param name="FieldIndex">第几个</param>
        /// <returns>若没有返回""</returns>
        public string GetASubField(string FieldTag, string SubTag, int FieldIndex)
        {
            string str = "";
            string[] strArray = this.m_Text.Split(new char[] { '\x001e' });
            int num = 0;
            string str2 = "";
            ArrayList list = new ArrayList();
            for (int i = 0; i <= (strArray.Length - 1); i++)
            {
                list.Add(strArray[i]);
            }
            for (int j = 0; j <= (list.Count - 1); j++)
            {
                str2 = list[j].ToString();
                if ((str2.Length > 3) && (str2.Substring(0, 3) == FieldTag))
                {
                    num++;
                    if (num == FieldIndex)
                    {
                        str2 = str2.Substring(4, str2.Length - 4);
                        int index = str2.IndexOf('\x001f' + SubTag);
                        if (index <= 0)
                        {
                            return str;
                        }
                        str2 = str2.Substring(index + 2, (str2.Length - index) - 2);
                        //Console.WriteLine("str21" + str2);
                        int length = str2.IndexOf('\x001f');
                        if (length == 0)
                            return str;
                        if (length >0)
                        {
                            str = str2.Substring(0, length);
                            //Console.WriteLine("str" + str);
                            str2 = str2.Substring(length - 1, (str2.Length - length) + 1);
                            //Console.WriteLine("str22" + str2);
                            return str;
                        }
                        return str2;
                    }
                }
            }
            return str;
        }
        /// <summary>
        /// 替换子字段内容，返回marc文本
        /// </summary>
        /// <param name="FieldTag">字段</param>
        /// <param name="SubTag">子字段</param>
        /// <param name="FieldIndex">第几个</param>
        /// <param name="Value">要替换的内容</param>
        public void ReplaceSubfield(string FieldTag, string SubTag, int FieldIndex, string Value)
        {
            string[] strArray = this.m_Text.Split(new char[] { '\x001e' });
            int num = 0;
            string str = "";
            ArrayList list = new ArrayList();
            bool flag = false;
            string str2 = "";
            for (int i = 0; i <= (strArray.Length - 1); i++)
            {
                list.Add(strArray[i]);
            }
            for (int j = 0; j < list.Count; j++)
            {
                str = list[j].ToString();//获取字段全部内容
                if (str.Length > 3)
                {
                    string str3 = str.Substring(0, 3);//获取字段名，即FieldTag，例如200
                    if (str3 == FieldTag)
                    {
                        num++;
                        if (num == FieldIndex)
                        {
                            flag = true;
                            str = str.Substring(3, str.Length - 3);//获取除字段名外的内容
                            string str4 = str3;
                            int index = str.IndexOf('\x001f' + SubTag);
                            if (index > 0)
                            {
                                string str5 = str.Substring(0, index + 2);//获取指示符到子字段之间的内容
                                str = str.Substring(index + 2, (str.Length - index) - 2);//获取子字段本身及其之后的内容
                                int startIndex = str.IndexOf('\x001f');
                                if (startIndex > 0)
                                {
                                    str = str.Substring(startIndex, str.Length - startIndex);//获取子字段内容之后的内容
                                    str2 = str4 + str5 + Value + str;
                                }
                                else
                                {
                                    str2 = str4 + str5 + Value;
                                }
                                list[j] = str2;
                            }
                            else
                            {
                                //不存在该子字段直接添加
                                list[j] = string.Concat(new object[] { list[j].ToString(), '\x001f', SubTag, Value });
                            }
                        }
                    }
                }
            }
            if (!flag)
            {
                //不存在字段直接添加
                list.Add(string.Concat(new object[] { FieldTag, "  ", '\x001f', SubTag, Value }));
            }
            str = "";
            for (int k = 0; k <= (list.Count - 1); k++)
            {
                if (list[k].ToString() != "")
                {
                    str = str + list[k].ToString() + '\x001e';
                }
            }
            this.m_Text = str;
        }
        /// <summary>
        /// 删除子字段，返回marc文本
        /// </summary>
        /// <param name="FieldTag">字段</param>
        /// <param name="SubTag">子字段</param>
        /// <param name="Index">第几个</param>
        public void DeleteField(string FieldTag, string SubTag, int Index)
        {
            string[] strArray = this.m_Text.Split(new char[] { '\x001e' });
            int num = 0;
            string str = "";
            ArrayList list = new ArrayList();
            for (int i = 0; i <= (strArray.Length - 1); i++)
            {
                list.Add(strArray[i]);
            }
            for (int j = 0; j <= (list.Count - 1); j++)
            {
                str = list[j].ToString();
                if ((str.Length > 3) && (str.Substring(0, 3) == FieldTag))
                {
                    num++;
                    if (num == Index)
                    {
                        int index = str.IndexOf('\x001f' + SubTag);
                        if (index > 0)
                        {
                            str = str.Replace('\x001f' + SubTag + GetASubField(FieldTag, SubTag, Index), "");
                            list[j] = str;
                        }
                    }
                }
            }
            str = "";
            for (int k = 0; k <= (list.Count - 1); k++)
            {
                str = str + list[k].ToString() + '\x001e';
            }
            this.m_Text = str;
        }
        /// <summary>
        /// 删除整个字段，返回marc文本
        /// </summary>
        /// <param name="FieldTag">字段</param>
        /// <param name="Index">第几个</param>
        public void DeleteField(string FieldTag, int Index)
        {
            string[] strArray = this.m_Text.Split(new char[] { '\x001e' });
            int num = 0;
            string str = "";
            ArrayList list = new ArrayList();
            for (int i = 0; i <= (strArray.Length - 1); i++)
            {
                list.Add(strArray[i]);
            }
            for (int j = 0; j <= (list.Count - 1); j++)
            {
                str = list[j].ToString();
                if ((str.Length > 3) && (str.Substring(0, 3) == FieldTag))
                {
                    num++;
                    if (num == Index)
                    {
                        list.RemoveAt(j);
                        break;
                    }
                }
            }
            str = "";
            for (int k = 0; k <= (list.Count - 1); k++)
            {
                str = str + list[k].ToString() + '\x001e';
            }
            this.m_Text = str;
        }
        /// <summary>
        /// 判断是否为目次区
        /// </summary>
        public bool isnumeric(string str)
        {
            char[] chArray = new char[str.Length];
            chArray = str.ToCharArray();
            for (int i = 0; i < chArray.Length; i++)
            {
                if ((chArray[i] < '0') || (chArray[i] > '9'))
                {
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 获取字符串长度，区分汉字
        /// </summary>
        /// <param name="strdata"></param>
        /// <returns></returns>
        private int GetStrLength(string strdata)
        {
            int num = 0;
            char[] chArray = strdata.ToCharArray();
            for (int i = 0; i <= (chArray.Length - 1); i++)
            {
                num += this.GetCharLength(chArray[i]);
            }
            return num;
        }
        private int GetCharLength(char ch)
        {
            int num = 0;
            if ((((short)ch) < 0) || (((short)ch) > 0x80))
            {
                return (num + 2);
            }
            num++;
            return num;
        }
        /// <summary>
        /// 字符串前补0
        /// </summary>
        /// <param name="Data"></param>
        /// <param name="Count"></param>
        /// <returns></returns>
        private string GetNumcCount(string Data, int Count)
        {
            int length = Data.Length;
            int num2 = Count - length;
            string str = "";
            for (int i = 1; i <= num2; i++)
            {
                str = "0" + str;
            }
            return (str + Data);
        }
        /// <summary>
        /// 文本转ISO
        /// </summary>
        public void SetISOStr()
        {
            string[] strArray = this.m_Text.Split(new char[] { '\x001e' });
            string strdata = "";
            string str2 = "nam0 22";
            string str3 = "";
            string data = "0";
            string str5 = "";
            for (int i = 0; i <= (strArray.Length - 1); i++)
            {
                if (strArray[i].ToString().Length > 3)
                {
                    strdata = strArray[i].ToString() + '\x001e';
                    if (this.isnumeric(strdata.Substring(0, 3)))
                    {
                        int num3 = this.GetStrLength(strdata) - 3;
                        str3 = str3 + strdata.Substring(0, 3) + this.GetNumcCount(num3.ToString(), 4) + this.GetNumcCount(data, 5);
                        str5 = str5 + strdata.Substring(3, strdata.Length - 3);
                        data = this.GetStrLength(str5).ToString();
                    }
                }
            }
            string l = (str3.Length + 25).ToString().PadLeft(5, '0');
            string sjq = string.Concat(new object[] { str2, str3, '\x001e', str5, '\x001d' });
            str2 = (GetStrLength(sjq) + 25).ToString().PadLeft(5, '0') + str2 + l + "   450 ";
            this.m_ISOData = string.Concat(new object[] { str2, str3, '\x001e', str5, '\x001d' });
        }
        /// <summary>
        /// 获取目次区的字符串
        /// </summary>
        /// <returns></returns>
        public string GetMuci()
        {
            char[] chArray = this.m_ISOData.ToCharArray();
            string str = null;
            for (int i = 0x18; i < this.m_ISOData.Length; i++)
            {
                str = str + chArray[i].ToString();
                if (chArray[i] == '\x001e')
                {
                    return str;
                }
            }
            return str;
        }
        private string GetHeader() =>
            this.m_ISOData.Substring(0, 0x18);
        /// <summary>
        /// 截取iso的内容
        /// </summary>
        /// <returns></returns>
        private string GetData()
        {
            int length = this.GetMuci().Length;
            int num2 = this.GetHeader().Length;
            int num3 = this.m_ISOData.Length;
            return this.m_ISOData.Substring(length + num2, (num3 - length) - num2);
        }
        public string GetFildData(int begin, int count)
        {
            string data = this.GetData();
            string str2 = "";
            string str4 = "";
            int num = 0;
            char[] chArray = data.ToCharArray();
            for (int i = 0; i < chArray.Length; i++)
            {
                if (num == begin)
                {
                    str2 = str2 + chArray[i].ToString();
                    char[] chArray2 = data.Substring(i, data.Length - i).ToCharArray();
                    int index = 0;
                    int num4 = 0;
                    while (index < chArray2.Length)
                    {
                        num4 += this.GetCharLength(chArray2[index]);
                        str4 = str4 + chArray2[index].ToString();
                        if (num4 == count)
                        {
                            return str4;
                        }
                        index++;
                    }
                    return str4;
                }
                num += this.GetCharLength(chArray[i]);
            }
            return str4;
        }
        /// <summary>
        /// ISO转文本
        /// </summary>
        public void SetISOtoMarc()
        {
            if (this.m_ISOData != "")
            {
                string str = "";
                string str2 = "";
                string muci = this.GetMuci();
                muci = muci.Substring(0, muci.Length - 1).Trim();
                string str4 = "";
                string str5 = "";
                string str6 = "";
                int startIndex = 0;
                while (startIndex < (muci.Length - 1))
                {
                    if (muci.Length >= startIndex)
                    {
                        str2 = muci.Substring(startIndex, 12);
                        str4 = str2.Substring(0, 3);
                        str5 = str2.Substring(3, 4);
                        str6 = str2.Substring(7, 5);
                        try
                        {
                            int s = int.Parse(str6.ToString());
                            try
                            {
                                int d = int.Parse(str5.ToString());
                                string nr = this.GetFildData(int.Parse(str6.ToString()), int.Parse(str5.ToString()));
                                if (!string.IsNullOrEmpty(nr))
                                    str = str + str4 + nr;
                            }
                            catch
                            {
                            }
                        }
                        catch
                        {
                        }
                    }
                    startIndex += 12;
                }
                this.m_Text = "nam0    " + '\x001e' + str;
            }
        }
        /// <summary>
        /// 获取字段的个数
        /// </summary>
        /// <param name="FieldTag"></param>
        /// <returns></returns>
        public int GetFieldCount(string FieldTag)
        {
            string[] strArray = this.m_Text.Split(new char[] { '\x001e' });
            int num = 0;
            for (int i = 0; i <= (strArray.Length - 1); i++)
            {
                if ((strArray[i].Length > 3) && (strArray[i].ToString().Substring(0, 3) == FieldTag))
                {
                    num++;
                }
            }
            return num;
        }

        /// <summary>
        /// 判断拼音字段，用于判断国图或calis
        /// </summary>
        /// <param name="str">9或A</param>
        /// <returns></returns>
        public bool PyBool(string str)
        {
            bool flag = false;
            if (this.m_Text.IndexOf('\x001f' + str) > 0)
                flag = true;
            return flag;
        }

        public void autoZD()
        {
            string zrz = this.GetASubField("200", "f", 1);
            string author = this.GetASubField("701", "a", 1).Trim();
            if (string.IsNullOrEmpty(author))
                author = this.GetASubField("711", "a", 1).Trim();
            if (string.IsNullOrEmpty(author))
            {
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.ConditionExpress = "键码=1";
                    string zrdy = _open.GetField("系统参数定义", "定义").ToString();
                    string[] zrds = zrdy.Split('@');
                    Array.Reverse(zrds);
                    if (!string.IsNullOrEmpty(zrz))
                    {
                        zrz = zrz.Replace("，", ",");
                        int qs = 0;
                        foreach (string str in zrds)
                        {
                            qs = zrz.LastIndexOf(str);
                            if (qs > -1)
                                break;
                        }
                        //Console.WriteLine("4wz:" + (zrz.Length - qs - 1).ToString()+":"+ zrz.Length+":"+qs);

                        string[] zrzs = zrz.Split(',');
                        for (int i = 0; i < zrzs.Length; i++)
                        {
                            string zr = zrzs[i];
                            if (i == zrzs.Length - 1)
                            {
                                foreach (string str in zrds)
                                {
                                    zr = zr.Replace(str, "");
                                }
                            }
                            this.ReplaceSubfield("701", "a", i + 1, zr);
                            if (qs > -1)
                            {
                                string zrfs = zrz.Substring(qs);
                                this.ReplaceSubfield("701", "4", i + 1, zrfs);
                            }
                        }
                    }
                    string fyz = this.GetASubField("200", "g", 1);
                    if (!string.IsNullOrEmpty(fyz))
                    {
                        fyz = fyz.Replace("，", ",");
                        int qs = 0;
                        foreach (string str in zrds)
                        {
                            qs = fyz.LastIndexOf(str);
                            if (qs > -1)
                                break;
                        }
                        string[] zrzs = fyz.Split(',');
                        for (int i = 0; i < zrzs.Length; i++)
                        {
                            string zr = zrzs[i];
                            if (i == zrzs.Length - 1)
                            {
                                foreach (string str in zrds)
                                {
                                    zr = zr.Replace(str, "");
                                }
                            }
                            this.ReplaceSubfield("702", "a", i + 1, zr);
                            if (qs > -1)
                            {
                                string fyfs = fyz.Substring(qs);
                                this.ReplaceSubfield("702", "4", i + 1, fyfs);
                            }
                        }
                    }
                }
            }
            this.ReplaceSubfield("801", "b", 1, "CCBUPT");
            this.ReplaceSubfield("905", "a", 1, "GSL");
            string F905D = "";
            string ygcd = this.GetASubField("905", "d", 1).Trim();
            if (string.IsNullOrEmpty(ygcd))
            {
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.ConditionExpress = "库键码=" + this._kjm;
                    string fld = _open.GetField("书目数据库定义", "中图分类字段").ToString().Trim();
                    F905D = this.GetASubField(fld.Substring(0, 3), fld.Substring(3), 1);
                    if(!string.IsNullOrEmpty(F905D))
                        this.ReplaceSubfield("905", "d", 1, F905D);
                }
            }
        }
    }
}
